<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable @close="handleClose">
    <el-form ref="formRef" :model="passwordForm" :rules="rules" label-width="100px">
      <el-form-item label="账号" prop="account">
        <el-input v-model="passwordForm.account" placeholder="请输入账号" disabled />
      </el-form-item>
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码" show-password clearable />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password clearable />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, reactive } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import mittBus from "@/utils/mittBus"
import { modifyPasswordApi } from "@/api/modules/login"
import { useUserStore } from "@/stores/modules/user"
import { encryptDes } from "@/utils/des"

const userStore = useUserStore()
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const passwordForm = reactive({
  account: "",
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
})

// 表单验证规则
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入密码不一致"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  oldPassword: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: "blur" }]
})

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true
  // 设置当前登录账号
  passwordForm.account = userStore.userInfo?.account || ""
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  passwordForm.oldPassword = ""
  passwordForm.newPassword = ""
  passwordForm.confirmPassword = ""
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 对密码进行 DES 加密
        const encryptedOldPassword = encryptDes(passwordForm.oldPassword)
        const encryptedNewPassword = encryptDes(passwordForm.newPassword)

        await modifyPasswordApi({
          account: passwordForm.account,
          oldPassword: encryptedOldPassword,
          newPassword: encryptedNewPassword
        })
        ElMessage.success("密码修改成功，请重新登录")
        handleClose()
        // 可以选择是否自动跳转到登录页
        // router.push("/login")
      } catch (error) {
        console.error("修改密码失败:", error)
        ElMessage.error("修改密码失败，请检查旧密码是否正确")
      }
    }
  })
}

watch(
  dialogVisible,
  val => {
    mittBus.emit("showBorad", val)
  },
  { immediate: true }
)

defineExpose({ openDialog })
</script>
